package com.pzh.assignment.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    private String secret;
    private int expire;

    /**
     * @description: 生成token
     * @param: map
     * @return: java.lang.String
     * @author pengzhihao
     * @date: 2022/3/25
     */
    public String generateToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        //设置载荷payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(getExpireTime()).sign(Algorithm.HMAC256(secret));
        return token;
    }

    public DecodedJWT getTokenInfo(String token){
        DecodedJWT info = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return info;
    }

    /**
     * @description: token完整性校验
     * @param: token
     * @return: void
     * @author pengzhihao
     * @date: 2022/3/25
     */
    public void verify(String token){
        JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }



    /**
     * @description: token是否过期
     * @param: expiration
     * @return: boolean
     * @author pengzhihao
     * @date: 2022/3/25
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    /**
     * @description: 生成过期时间
     * @return: java.util.Date
     * @author pengzhihao
     * @date: 2022/4/2
     */
    public Date getExpireTime(){
        Calendar instance = Calendar.getInstance();
        //设置过期时间
        instance.add(Calendar.DATE, expire);
        return instance.getTime();
    }
}
